< previous page page_192 next page >

Page 192
The sourcestr in this case is the string that receives the replacement characters. sourcestr must be a string variable; it cannot be a literal string or string function. startpos is the character position at which the replacement starts. This position must be an integer number greater than zero. numchars is an optional argument that specifies the number of characters from the replacement string being used by the function. replstr represents the string containing the replacement characters. This string can be a string variable, a literal string, or a string function.
The Mid statement preserves the original length of the string. In other words, if the space remaining between the starting position and the end of the string is less than the length of the replacement string, only the leftmost characters are used from the replacement string.
You will find a number of uses for the Mid statement in your programs. Remember the capitalization example in Listing 9.3? Using the Mid statement, you can perform the same function with the following code:
Dim sWord as String, sProperWord as String
sWord="mIxEd CaSe"
sProperWord = LCase$(sWord)
Mid(sProperWord,1) = UCase$(Left$(sWord,1))
In another program, I needed to eliminate any carriage return or line feed characters that were embedded in a string to keep them from causing printing problems. I used the Mid statement to replace these characters with a space. This example is shown in Listing 9.6.
Listing 9.6 REPLACE.ZIPUsing the Mid Statement to Eliminate Specific Characters in a String
'Replace Line feeds with spaces
    nFindPos = 0
    Do
      nFindPos = InStr(sInput, Chr$(10))
      If nFindPos > 0 Then Mid(sInput, nFindPos) = " "
    Loop Until nFindPos = 0

'Replace Carriage returns with spaces
    nFindPos = 0
    Do
      nFindPos = InStr(sInput, Chr$(13))
      If nFindPos > 0 Then Mid(sInput, nFindPos) = " "
    Loop Until nFindPos = 0
Note that the code in Listing 9.6 modifies the source string; that is, it actually changes characters in the string sInput. Visual Basic now includes the Replace function, which returns a string with the characters replaced. The syntax is
outString = Replace(inString, searchString, _
replacewith[, start[, count[, compare]]])

 
< previous page page_192 next page >